<?php

namespace App\Http\Controllers\School;

use App\Http\Resources\School\BookOrderResource;
use App\Models\BookOrder;
use App\Models\SchoolAdminLog;
use App\Services\BookOrderService;
use Illuminate\Http\Request;

/**
 * Class BookOrderController
 * @package App\Http\Controllers\School
 * 学校后台订单管理
 */
class BookOrderController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 订单列表
     */
    public function index(Request $request)
    {
        $bookOrders = BookOrder::orderBy('created_at', 'desc')
            ->besideOfficialOrder()
            ->where('school_id', \Auth::user()->school_id)
            ->with('rule')->with('user.role')
            ->selectStatus($request->status)
            ->typeIs($request->orderType)
            ->eatTypeIs($request->eat_type)
            ->eatDateIs($request->eat_date)
            ->eatNameLike($request->eat_name)
            ->eatPhoneIs($request->eat_phone)
            ->calculatedIs($request->is_calculated)
            ->priceRuleIs($request->price_rule);
        if ($request->type === 'export') {
            $data = $bookOrders->get();
        } else {
            $data = $bookOrders->paginate($request->size);
        }
        return BookOrderResource::collection($data);
    }

    /**
     * @param Request $request
     * @param BookOrder $bookOrder
     * @return BookOrderResource|array
     */
    public function update(Request $request, BookOrder $bookOrder)
    {
        $status = '';
        if ($request->type === 'making') {
            $bookOrder = BookOrderService::making($bookOrder);
        } elseif ($request->type === 'complete') {
            $bookOrder = BookOrderService::finished($bookOrder);
        } elseif ($request->type === 'cancel') {
            // 已结算的订单不能取消
            if ($bookOrder->is_calculated === BookOrder::CALCULATED) {
                return $this->fail('已结算的订单不能取消');
            }
            $bookOrder = BookOrderService::backendCancel($bookOrder);
        }
        if ($request->status === BookOrder::ORDER_STATUS_INIT) {
            $status = '已提交';
        }
        if ($request->status === BookOrder::ORDER_STATUS_MAKING) {
            $status = '制作中';
        }
        if ($request->status === BookOrder::ORDER_STATUS_COMPLETED) {
            $status = '已完成';
        }
        SchoolAdminLog::Log('修改订单状态: id - ' . $bookOrder->id . ', ' . $status . ' => ' . $bookOrder->getStatusLabelAttribute());
        return new BookOrderResource($bookOrder);
    }
}
